from fastapi import APIRouter, Depends
from sqlalchemy.orm.session import Session
from ..dependencies import get_current_active_user, get_db
from .. import schemas
from ..crud import users
from . import models

router = APIRouter(
    prefix='/users',
    tags=['用户'],
)


@router.post('/create', response_model=models.user_return)
def create_user(user: schemas.Users_Create, db: Session = Depends(get_db)):
    return models.user_return(
        code=0,
        message='已创建用户',
        user=users.create_user(db, user=user)
    )


# 用户修改基本信息 需要先验证current_user,再直接进行修改
@router.post('/update', response_model=models.user_return)
def update_user(user: schemas.User_Update, db: Session = Depends(get_db),
                   current_user: schemas.Users = Depends(get_current_active_user)):

    return models.user_return(
        code=0 if current_user else 1,
        message='已更新用户信息' if current_user else '当前用户未认证或认证出错',
        user=users.update_user(db, user, current_user)

        )


@router.get('/get', response_model=models.user_return)
def retrieve_user(user_id: int, db: Session = Depends(get_db),
                  current_user: schemas.Users = Depends(get_current_active_user)):
    db_user = users.get_user(db, user_id=user_id)

    return models.user_return(
        code=0 if db_user else 1,
        message='已找到用户' if db_user else '未找到用户',
        user=db_user
    )


@router.get('/get/self', response_model=models.user_return)
async def retrieve_myself(current_user: schemas.Users = Depends(get_current_active_user)):
    return models.user_return(
        code=0,
        message='已找到用户',
        user=current_user
    )


@router.get('/gets', response_model=models.users_return)
def retrieve_users(limit: int = 10, offset: int = 0, db: Session = Depends(get_db)):
    db_users = users.get_users(db, limit, offset)
    return models.users_return(
        code=1 if db_users == [] else 0,
        message='未找到用户' if db_users == [] else '已找到用户',
        users=db_users
    )
